package com.interview.a_多线程.e_Thread和Object中的重要方.c_wait_只释放当前_monitor;

/**
 * Monitor
 * <p>
 * 证明 wait 只释放当前锁
 */
public class WaitMonitor {
    public static Object lock_A = new Object();
    public static Object lock_B = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (lock_A) {
                System.out.println(Thread.currentThread().getName() + " 取锁lock_A成功\n");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock_B) {
                    System.out.println(Thread.currentThread().getName() + " 取锁lock_B成功\n");
                    try {
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName() + " 释放 锁lock_A\n");
                        lock_A.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                synchronized (lock_A) {
                    System.out.println(Thread.currentThread().getName() + " 取锁lock_A成功\n");
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " 正在尝试获取lock_B...\n");
                    synchronized (lock_B) {
                        System.out.println(Thread.currentThread().getName() + " 取锁lock_B成功\n");
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        thread1.start();
        thread1.setName("线程1");

        Thread2 thread2 = new Thread2();
        thread2.start();
        thread2.setName("线程2");


    }
}

